package com.aiyige.page.publish.traingcard;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.eventbus.EventCopyTraingCardFinish;
import com.aiyige.base.eventbus.EventEditTraingCardFinish;
import com.aiyige.page.publish.adapter.FormCourseAdapter;
import com.aiyige.page.publish.adapter.FormTagAdapter;
import com.aiyige.page.publish.coursesingleprice.CourseSinglePricePage;
import com.aiyige.page.publish.selectcourse.SelectCoursePage;
import com.aiyige.page.publish.selectcourse.model.Course;
import com.aiyige.page.publish.selecttag.SelectTagPage;
import com.aiyige.page.publish.selecttag.model.SelectTagItem;
import com.aiyige.page.publish.traingcard.model.TraingCardFormModel;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.utils.CancelEditDialogUtil;
import com.aiyige.utils.ExcludeEmojiInputFilter;
import com.aiyige.utils.ExcludeSpaceInputFilter;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.KeyboardUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.TextWatcherAdapter;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = ARouterConfig.PublishTraingCardFormPage, extras = ARouterConfig.EXTRA_NEED_LOGIN | ARouterConfig.EXTRA_NEED_BINDPHONE)
public class PublishTraingCardFormPage extends AppCompatActivity {
    public static final int REQUEST_CODE_SELECT_TAG = 1;
    public static final int REQUEST_CODE_SELECT_COURSE = 2;
    public static final int REQUEST_CODE_NEXT = 3;
    public static final int REQUEST_CODE_EDIT_SINGLE_COURSE_PRICE = 4;

    @Autowired
    TraingCardFormModel formModel = null;

    CommonBottomDialogFragment cardTypeDialog;
    CommonBottomDialogFragment effectiveTypeDialog;

    FormTagAdapter formTagAdapter;
    FormCourseAdapter formCourseAdapter;
    @BindView(R.id.containerLayout)
    View containerLayout;
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleEt)
    EditText titleEt;
    @BindView(R.id.formTitleLayout)
    RelativeLayout formTitleLayout;
    @BindView(R.id.traingCardTypeTv)
    TextView traingCardTypeTv;
    @BindView(R.id.traingCardTypeLayout)
    RelativeLayout traingCardTypeLayout;
    @BindView(R.id.usageCountEt)
    EditText usageCountEt;
    @BindView(R.id.usageCountLayout)
    RelativeLayout usageCountLayout;
    @BindView(R.id.usageCountContainer)
    ExpandableLayout usageCountContainer;
    @BindView(R.id.effectiveTypeTv)
    TextView effectiveTypeTv;
    @BindView(R.id.effectiveTypeLayout)
    RelativeLayout effectiveTypeLayout;
    @BindView(R.id.validityEt)
    EditText validityEt;
    @BindView(R.id.validityLayout)
    RelativeLayout validityLayout;
    @BindView(R.id.priceEt)
    EditText priceEt;
    @BindView(R.id.priceLayout)
    RelativeLayout priceLayout;
    @BindView(R.id.platformDividendEt)
    EditText platformDividendEt;
    @BindView(R.id.platformDividendLayout)
    RelativeLayout platformDividendLayout;
    @BindView(R.id.platformDividendDescContainer)
    ExpandableLayout platformDividendDescContainer;
    @BindView(R.id.tagTv)
    TextView tagTv;
    @BindView(R.id.tagRv)
    RecyclerView tagRv;
    @BindView(R.id.tagLayout)
    RelativeLayout tagLayout;
    @BindView(R.id.courseTv)
    TextView courseTv;
    @BindView(R.id.courseLayout)
    RelativeLayout courseLayout;
    @BindView(R.id.courseRv)
    RecyclerView courseRv;
    @BindView(R.id.courseSinglePriceTv)
    TextView courseSinglePriceTv;
    @BindView(R.id.courseSinglePriceLayout)
    RelativeLayout courseSinglePriceLayout;
    @BindView(R.id.courseSinglePriceContainer)
    ExpandableLayout courseSinglePriceContainer;
    @BindView(R.id.nextBtn)
    TextView nextBtn;
    KeyboardUtil.KeyboardMonitor keyboardMonitor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_publish_traing_card_form);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (formModel == null) {
            finish();
            return;
        }
        switch (formModel.getOperationType()) {
            case PublishUtil.OPERATION_TYPE_EDIT:
                titleTv.setText(R.string.edit_traing_card);
                break;
            default:
                titleTv.setText(R.string.publish_traing_card);
                break;
        }
        initView();
        updateView();
    }

    @Override
    protected void onDestroy() {
        keyboardMonitor.uninstall();
        super.onDestroy();
    }

    void initView() {
        keyboardMonitor = KeyboardUtil.KeyboardMonitor.newBuilder()
                .container(containerLayout)
                .callback(new KeyboardUtil.KeyboardMonitor.Callback() {
                    @Override
                    public void onKeyboardShow() {
                        nextBtn.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onKeyboardHide() {
                        nextBtn.setVisibility(View.VISIBLE);
                        containerLayout.requestFocus();
                    }
                })
                .build()
                .install();
        titleEt.setFilters(new InputFilter[]{new ExcludeSpaceInputFilter(), new ExcludeEmojiInputFilter(), new InputNumFilter(30, false)});
        tagRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        formTagAdapter = new FormTagAdapter();
        formTagAdapter.bindToRecyclerView(tagRv);
        formTagAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.deleteBtn:
                        adapter.remove(position);
                        break;
                }
            }
        });
        courseRv.setLayoutManager(new GridLayoutManager(this, 3));
        formCourseAdapter = new FormCourseAdapter();
        formCourseAdapter.bindToRecyclerView(courseRv);
        formCourseAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.deleteBtn:
                        adapter.remove(position);
                        break;
                }
            }
        });

        titleEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                formModel.setTitle(s.toString());
            }
        });

        validityEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        int value = Integer.parseInt(validityEt.getText().toString());
                        if (value <= 0) {
                            throw new Exception();
                        }
                        formModel.setValidity(String.valueOf(value));
                    } catch (Exception e) {
                        ToastX.show(R.string.invalid_integer);
                        formModel.setValidity(null);
                    }
                    updateView();
                }
            }
        });


        priceEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        String valueStr = priceEt.getText().toString().trim();
                        double value = Double.parseDouble(valueStr);
                        if (value < 0) {
                            throw new Exception();
                        }
                        formModel.setPrice(StringUtils.priceFormatEscapeRedundantTailZero(value));
                    } catch (Exception e) {
                        ToastX.show(R.string.invalid_price);
                        formModel.setPrice(null);
                    }
                    updateView();
                }
            }
        });

        usageCountEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        int value = Integer.parseInt(usageCountEt.getText().toString());
                        if (value <= 0) {
                            throw new Exception();
                        }
                        formModel.setUsageCount(String.valueOf(value));
                    } catch (Exception e) {
                        ToastX.show(R.string.invalid_integer);
                        formModel.setUsageCount(null);
                    }
                    updateView();
                }
            }
        });


        platformDividendEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    try {
                        String valueStr = platformDividendEt.getText().toString().trim();
                        double dividend = Double.parseDouble(valueStr);
                        if (dividend / 100 < PublishUtil.MIN_PLATFORM_DIVIDEND) {
                            throw new Exception("");
                        }
                        if (dividend / 100 > 1) {
                            throw new Exception("");
                        }
                        formModel.setPlatformDividend(StringUtils.priceFormatEscapeRedundantTailZero(dividend));
                    } catch (Exception e) {
                        ToastX.show(R.string.invalid_platform_dividend);
                        formModel.setPlatformDividend(null);
                    }
                    updateView();
                }
            }
        });

        cardTypeDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.traing_card_type_dialog)
                .viewIdList(R.id.timeCardBtn, R.id.countCardBtn, R.id.prepaidCardBtn, R.id.cancelBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        int cardType;
                        switch (view.getId()) {
                            case R.id.timeCardBtn:
                                cardType = TraingCardFormModel.CARD_TYPE_TIME_CARD;
                                break;
                            case R.id.countCardBtn:
                                cardType = TraingCardFormModel.CARD_TYPE_COUNT_CARD;
                                break;
                            case R.id.prepaidCardBtn:
                                cardType = TraingCardFormModel.CARD_TYPE_PREPAID_CARD;
                                break;
                            default:
                                cardType = TraingCardFormModel.CARD_TYPE_COUNT_CARD;
                                break;
                        }
                        if (formModel.getCardType() == null || formModel.getCardType() != cardType) {
                            formModel.setCourseList(new LinkedList<Course>());
                        }
                        formModel.setCardType(cardType);
                        updateView();
                    }
                })
                .build();

        effectiveTypeDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.traing_card_effective_type_dialog)
                .viewIdList(R.id.immediateBtn, R.id.cancelBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.immediateBtn:
                                formModel.setEffectiveType(TraingCardFormModel.EFFECTIVE_TYPE_IMMEDIATE);
                                break;
                        }
                        updateView();
                    }
                })
                .build();
    }

    public void updateView() {
        titleEt.setText(formModel.getTitle());
        if (formModel.getCardType() != null) {
            switch (formModel.getCardType()) {
                case TraingCardFormModel.CARD_TYPE_COUNT_CARD:
                    traingCardTypeTv.setText(R.string.count_card_option);
                    usageCountContainer.expand();
                    courseSinglePriceContainer.collapse();
                    break;
                case TraingCardFormModel.CARD_TYPE_TIME_CARD:
                    traingCardTypeTv.setText(R.string.time_card_option);
                    usageCountContainer.collapse();
                    courseSinglePriceContainer.collapse();
                    break;
                case TraingCardFormModel.CARD_TYPE_PREPAID_CARD:
                    traingCardTypeTv.setText(R.string.prepaid_card_option);
                    usageCountContainer.collapse();
                    courseSinglePriceContainer.expand();
                    break;
            }
        } else {
            traingCardTypeTv.setText("");
            usageCountContainer.collapse(false);
            courseSinglePriceContainer.collapse(false);
        }
        if (formModel.getEffectiveType() != null) {
            switch (formModel.getEffectiveType()) {
                case TraingCardFormModel.EFFECTIVE_TYPE_ATTENDANCE:
                    effectiveTypeTv.setText(R.string.attendance_effective);
                    break;
                case TraingCardFormModel.EFFECTIVE_TYPE_IMMEDIATE:
                    effectiveTypeTv.setText(R.string.immediate_effective);
                    break;
            }
        } else {
            effectiveTypeTv.setText("");
        }
        validityEt.setText(formModel.getValidity());
        priceEt.setText(formModel.getPrice());
        platformDividendEt.setText(formModel.getPlatformDividend());
        formTagAdapter.setNewData(formModel.getSelectTagItemList());
        if (ListUtil.isEmpty(formModel.getSelectTagItemList())) {
            tagTv.setVisibility(View.VISIBLE);
        } else {
            tagTv.setVisibility(View.INVISIBLE);
        }
        formCourseAdapter.setNewData(formModel.getCourseList());
        if (ListUtil.isEmpty(formModel.getCourseList())) {
            courseTv.setVisibility(View.VISIBLE);
        } else {
            courseTv.setVisibility(View.INVISIBLE);
        }
        usageCountEt.setText(formModel.getUsageCount());
    }

    boolean checkFormValidate() {
        boolean result = true;
        if (TextUtils.isEmpty(formModel.getTitle())) {
            result = false;
            formTitleLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            formTitleLayout.setBackgroundResource(R.color.white);
        }

        if (formModel.getCardType() == null) {
            result = false;
            traingCardTypeLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            traingCardTypeLayout.setBackgroundResource(R.color.white);
        }

        if (formModel.getCardType() != null && formModel.getCardType() == TraingCardFormModel.CARD_TYPE_COUNT_CARD) {
            if (TextUtils.isEmpty(formModel.getUsageCount())) {
                result = false;
                usageCountLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
            } else {
                usageCountLayout.setBackgroundResource(R.color.white);
            }
        }

        if (formModel.getEffectiveType() == null) {
            result = false;
            effectiveTypeLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            effectiveTypeLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getValidity())) {
            result = false;
            validityLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            validityLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getPrice())) {
            result = false;
            priceLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            priceLayout.setBackgroundResource(R.color.white);
        }

        if (TextUtils.isEmpty(formModel.getPlatformDividend())) {
            result = false;
            platformDividendLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
        } else {
            platformDividendLayout.setBackgroundResource(R.color.white);
        }


        if (formModel.getCardType() != null && formModel.getCardType() == TraingCardFormModel.CARD_TYPE_PREPAID_CARD) {
            boolean notSetSinglePrice = false;
            for (Course course : formModel.getCourseList()) {
                if (TextUtils.isEmpty(course.getSinglePrice())) {
                    notSetSinglePrice = true;
                    break;
                }
            }
            if (notSetSinglePrice) {
                result = false;
                courseSinglePriceLayout.setBackgroundResource(R.color.zwcolor_red_fff9fa);
            } else {
                courseSinglePriceLayout.setBackgroundResource(R.color.white);
            }
        }


        if (!result) {
            ToastX.show(R.string.unfinish_form);
        }
        return result;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_SELECT_TAG: {
                if (resultCode == RESULT_OK) {
                    formModel.getSelectTagItemList().add(SelectTagItem.newBuilder()
                            .id(data.getStringExtra(SelectTagPage.EXTRA_KEY_SELECTED_TAG_ID))
                            .name(data.getStringExtra(SelectTagPage.EXTRA_KEY_SELECTED_TAG_NAME))
                            .build());
                }
                break;
            }
            case REQUEST_CODE_SELECT_COURSE: {
                if (resultCode == RESULT_OK) {
                    List<Course> courseList = data.getParcelableArrayListExtra(SelectCoursePage.EXTRA_KEY_SELECT_COURSE_DATA);
                    formModel.setCourseList(courseList);
                }
                break;
            }
            case REQUEST_CODE_EDIT_SINGLE_COURSE_PRICE: {
                if (resultCode == RESULT_OK) {
                    List<Course> courseList = data.getParcelableArrayListExtra(CourseSinglePricePage.EXTRA_KEY_COURSE_SINGLE_PRICE_DATA);
                    formModel.setCourseList(courseList);
                }
                break;
            }

            case REQUEST_CODE_NEXT: {
                if (resultCode == RESULT_OK) {
                    setResult(RESULT_OK, data);
                    finish();
                }
                break;
            }
            default: {
                super.onActivityResult(requestCode, resultCode, data);
                break;
            }
        }
        updateView();
    }

    @Override
    public void onBackPressed() {
        CancelEditDialogUtil.newbuilder(this)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        EventBus.getDefault().post(EventEditTraingCardFinish.newBuilder()
                                .resultCode(EventEditTraingCardFinish.RESULT_CANCEL)
                                .build());
                        EventBus.getDefault().post(EventCopyTraingCardFinish.newBuilder()
                                .resultCode(EventCopyTraingCardFinish.RESULT_CANCEL)
                                .build());
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create()
                .show();
    }

    @OnClick({R.id.titleBackBtn, R.id.formTitleLayout, R.id.traingCardTypeLayout, R.id.usageCountLayout, R.id.effectiveTypeLayout, R.id.validityLayout, R.id.tagLayout, R.id.courseLayout, R.id.courseSinglePriceLayout, R.id.nextBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                CancelEditDialogUtil.newbuilder(this)
                        .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                                EventBus.getDefault().post(EventEditTraingCardFinish.newBuilder()
                                        .resultCode(EventEditTraingCardFinish.RESULT_CANCEL)
                                        .build());
                                EventBus.getDefault().post(EventCopyTraingCardFinish.newBuilder()
                                        .resultCode(EventCopyTraingCardFinish.RESULT_CANCEL)
                                        .build());
                            }
                        })
                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create()
                        .show();
                break;
            case R.id.traingCardTypeLayout:
                cardTypeDialog.show(getSupportFragmentManager(), "");
                containerLayout.requestFocus();
                break;
            case R.id.effectiveTypeLayout:
                effectiveTypeDialog.show(getSupportFragmentManager(), "");
                containerLayout.requestFocus();
                break;
            case R.id.tagLayout:
                if (formModel.getSelectTagItemList().size() < PublishUtil.MAX_PUBLISH_TAG_NUM) {
                    String[] selectedIds = new String[formTagAdapter.getData().size()];
                    for (int i = 0; i < selectedIds.length; ++i) {
                        selectedIds[i] = formTagAdapter.getData().get(i).getId();
                    }
                    ARouter.getInstance()
                            .build(ARouterConfig.SelectTagPage)
                            .withObject("selectedIds", selectedIds)
                            .navigation(this, REQUEST_CODE_SELECT_TAG);
                } else {
                    ToastX.show(String.format(getString(R.string.reach_max_tag_select_num), PublishUtil.MAX_PUBLISH_TAG_NUM));
                }
                containerLayout.requestFocus();
                break;
            case R.id.courseLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.SelectCoursePage)
                        .withInt("cardType", formModel.getCardType() == null ? TraingCardFormModel.CARD_TYPE_UNKNOWN : formModel.getCardType())
                        .withObject("selectedCourses", formModel.getCourseList())
                        .navigation(this, REQUEST_CODE_SELECT_COURSE);
                containerLayout.requestFocus();
                break;
            case R.id.courseSinglePriceLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.CourseSinglePricePage)
                        .withObject("courses", formModel.getCourseList())
                        .navigation(this, REQUEST_CODE_EDIT_SINGLE_COURSE_PRICE);
                containerLayout.requestFocus();
                break;
            case R.id.nextBtn:
                if (checkFormValidate()) {
                    ARouter.getInstance()
                            .build(ARouterConfig.CourseDescriptionPage)
                            .withParcelable("traingCardFormModel", formModel)
                            .navigation(this, REQUEST_CODE_NEXT);
                }
                break;
        }
    }
}
